package org.yate.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.yate.oa.model.LoginEntity;
import org.yate.oa.model.MessageEntity;
import org.yate.oa.model.OrgEntity;
import org.yate.oa.model.RelationEntity;
import org.yate.oa.model.RestDayEntity;
import org.yate.oa.model.TaskEntity;
import org.yate.oa.model.UserEntity;
import org.yate.oa.service.IMessageService;
import org.yate.oa.service.IOrgService;
import org.yate.oa.service.IRelationService;
import org.yate.oa.service.IRestDayService;
import org.yate.oa.service.ITaskService;
import org.yate.oa.service.imp.MessageService;
import org.yate.oa.service.imp.OrgService;
import org.yate.oa.service.imp.RelationService;
import org.yate.oa.service.imp.RestDayService;
import org.yate.oa.service.imp.TaskService;
import org.yate.oa.utils.Pagination;
import org.yate.oa.utils.TaskStatus;
import org.yate.oa.utils.TaskType;

import com.alibaba.fastjson.JSONObject;

/**
 * 任务管理
 * 
 * @author ZYY
 * 
 */
@WebServlet(urlPatterns = { "/task/get", "/task/post", "/task/put", "/task/delete" }, asyncSupported = false)
public class TaskController extends BaseServletController {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		doPost(req, rsp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		String type = req.getParameter("type");
		if (StringUtils.isEmpty(type)) {
		}
		if (type.equals("add")) {
			makeTask(req, rsp);
		} else if (type.equals("get")) {
			getTask(req, rsp);
		} else if (type.equals("restday")) {
			getRestDay(req, rsp);
		} else if (type.equals("resetTask")) {
			resetTask(req, rsp);
		}
	}

	/**
	 * 发起任务
	 * 
	 * @param req
	 * @param rsp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void makeTask(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		LoginEntity le = (LoginEntity) req.getSession().getAttribute("user");
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		if (le == null) {
			json.put("code", "401");
			json.put("msg", "current user is null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		String taskType = req.getParameter("taskType");
		long beginDate = Long.parseLong(req.getParameter("beginDate"));
		long endDate = Long.parseLong(req.getParameter("endDate") == null ? "0" : req.getParameter("endDate"));
		int isKF = Boolean.parseBoolean(req.getParameter("isKF") == null ? "false" : req.getParameter("isKF")) ? 1 : 0;
		Float days = Float.parseFloat(req.getParameter("days") == null ? "0" : req.getParameter("days"));
		String remark = req.getParameter("remark");
		String leaveType = req.getParameter("leaveType");
		IOrgService orgService = this.springCtx.getBean(OrgService.class);
		IRelationService relationService = this.springCtx.getBean(RelationService.class);
		RelationEntity re = new RelationEntity();
		re.setUserId(le.getUserId());
		re = relationService.getEntityBy(re);
		OrgEntity oe = orgService.getEntity(re.getOrgId());
		UserEntity userEntity = new UserEntity();
		userEntity.setId(le.getUserId());
		if (oe.getManagerId() == null || oe.getManagerId().intValue() == le.getUserId().intValue()) {
			oe = orgService.getEntity(oe.getParentOrgId());
		}
		int nextApprovalId = (oe.getManagerId() == null ? 22 : oe.getManagerId().intValue());
		TaskEntity te = new TaskEntity(userEntity, taskType, new Date(beginDate), days, new Date(endDate), le.getUserId(), nextApprovalId, TaskStatus.processing.name(), remark, leaveType, isKF);
		ITaskService taskService = this.springCtx.getBean(TaskService.class);
		taskService.add(te);
		// 生成新消息通知部门助理
		try {
			String taskName = "";
			if (taskType.equals(TaskType.leave.name())) {
				taskName = "请假";
			} else if (taskType.equals(TaskType.paidleave.name())) {
				taskName = "调休";
			} else if (taskType.equals(TaskType.workovertime.name())) {
				taskName = "加班";
			}
			Integer targetUserId = Integer.parseInt(req.getSession().getAttribute("zlid").toString());
			IMessageService msvr = this.springCtx.getBean(MessageService.class);
			MessageEntity me = new MessageEntity(0, targetUserId, le.getUsername() + "发起了" + taskName + "申请。", 0);
			msvr.add(me);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		json.put("code", "200");
		json.put("msg", "succsss");
		out.println(json);
		out.flush();
		out.close();
	}

	private void getTask(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		LoginEntity le = (LoginEntity) req.getSession().getAttribute("user");
		if (le == null) {
			json.put("status", "401");
			json.put("data", "current user is null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		ITaskService servie = this.springCtx.getBean(TaskService.class);
		String taskType = req.getParameter("taskType");
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		String[] strs = { le.getUserId() + "", taskType };
		Pagination<TaskEntity> data = servie.getEntitiesByOrdId(pageIndex, 10, "", "", strs); // .getEntities(pageIndex,
																								// 10,
																								// "",
																								// "");
		json.put("status", "200");
		json.put("data", data);
		out.println(json);
		out.flush();
		out.close();
	}

	private void getRestDay(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		LoginEntity le = (LoginEntity) req.getSession().getAttribute("user");
		if (le == null) {
			json.put("code", "401");
			json.put("data", "current user is null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		IRestDayService service = this.springCtx.getBean(RestDayService.class);
		RestDayEntity rde = new RestDayEntity();
		if (service.checkUserExist(le.getUserId())) {
			rde = service.getEntity(le.getUserId());
		} else {
			UserEntity u = new UserEntity();
			u.setId(le.getUserId());
			rde.setUserEntity(u);
			rde.setRestDay(Double.valueOf("0"));
			rde.setLeaveDay(Double.valueOf("0"));
			service.add(rde);
		}
		json.put("code", "200");
		json.put("data", rde);
		out.println(json);
		out.flush();
		out.close();
	}

	/** 撤销申请 **/
	private void resetTask(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		PrintWriter out = rsp.getWriter();
		JSONObject json = new JSONObject();
		int id = Integer.parseInt(req.getParameter("id"));
		ITaskService svr = this.springCtx.getBean(TaskService.class);
		svr.remove(id);
		json.put("code", "200");
		json.put("data", "撤销成功");
		out.println(json);
		out.flush();
		out.close();
	}
}
